package cn.chowx.myjfinal.common;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.chowx.myjfinal.help.PageHelp;

import com.google.common.base.Strings;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;


@SuppressWarnings({ "rawtypes", "serial" })
public class BaseModel<B extends BaseModel> extends Model<B> {
	/**
	 * 分页
	 * @param pageHelp
	 * @param tableName
	 * @return
	 */
	public Page<B> findPage(PageHelp pageHelp, String tableName){
		StringBuilder sb = new StringBuilder(); 
		sb.append("from ").append(tableName).append(" where 1=1 ");
		sb.append(PageHelp.buildSearchSQL(pageHelp,null));
		if(!Strings.isNullOrEmpty(pageHelp.getSidx())){
			sb.append(" order by ").append(pageHelp.getSidx());
			if(!Strings.isNullOrEmpty(pageHelp.getSord())){
				sb.append(" ").append(pageHelp.getSord());
			}
		}else{
			sb.append(" order by id asc");
		}
		
		String sqlExceptSelect = sb.toString();
		Page<B> page = paginate(pageHelp.getPageNum(), pageHelp.getRows(), "select * ", sqlExceptSelect);
		return page;
	}
	
	/**
	 * 获取 json 格式的数据,供 jqgrid 在页面使用.
	 * @param pageHelp
	 * @param tableName
	 * @return
	 */
	public String getJqGridMap(PageHelp pageHelp, String tableName){
		Page<B> page = findPage(pageHelp, tableName);
		if(tableName.equals(TableName.SysUser.getTableName())){
			List<B> list = page.getList();
			for(B b : list){
				b.remove("password");  //过滤掉用户表里的密码字段,以免传送到客户端.
			}
		}
		
		Map<String,Object> root = new HashMap<>();
		root.put("total", page.getTotalPage());
		root.put("page", page.getPageNumber());
		root.put("records", page.getTotalRow());
		root.put("rows", page.getList());
		return JsonKit.toJson(root);
	}
}
